import bullet from '../canvas/bullet'
import player from '../canvas/player'
import { DirectionEnum } from '../enum/directionEnum'
import { image, ImageMapKey } from '../service/image'
import util from '../util'
import ModelAbstract from './modelAbstract'

export default class PlayerModel extends ModelAbstract implements IModel {
  canvas: ICanvas = player
  name: string = 'player'
  isBindEvent: boolean = false

  image(): HTMLImageElement {
    const playerDirection = (this.name + this.direction) as ImageMapKey

    return image.get(playerDirection)!
  }
  render(): void {
    super.draw()
    if (!this.isBindEvent) {
      this.isBindEvent = true
      // 键盘事件
      document.addEventListener('keydown', this.changeDirection.bind(this))
      document.addEventListener('keydown', this.move.bind(this))
      // 发射子弹
      document.addEventListener('keydown', (event: KeyboardEvent) => {
        if (event.code === 'Space') {
          bullet.addPlayerBullet()
        }
      })
    }
  }

  changeDirection(event: KeyboardEvent) {
    // switch case ,case只能写一个值，不能写表达式。
    switch (event.code) {
      case 'ArrowUp':
        this.direction = DirectionEnum.Top
        break
      case 'KeyW':
        this.direction = DirectionEnum.Top
        break
      case 'ArrowRight':
        this.direction = DirectionEnum.Right
        break
      case 'KeyD':
        this.direction = DirectionEnum.Right
        break
      case 'ArrowDown':
        this.direction = DirectionEnum.Bottom
        break
      case 'KeyS':
        this.direction = DirectionEnum.Bottom
        break
      case 'ArrowLeft':
        this.direction = DirectionEnum.Left
        break
      case 'KeyA':
        this.direction = DirectionEnum.Left
        break
    }

    this.canvas.renderModels()
  }

  move(event: KeyboardEvent) {
    let x = this.x
    let y = this.y

    switch (event.code) {
      case 'ArrowUp':
        y -= 5
        break
      case 'KeyW':
        y -= 5
        break
      case 'ArrowRight':
        x += 5
        break
      case 'KeyD':
        x += 5
        break
      case 'ArrowDown':
        y += 5
        break
      case 'KeyS':
        y += 5
        break
      case 'ArrowLeft':
        x -= 5
        break
      case 'KeyA':
        x -= 5
        break
    }

    // 碰撞检测
    if (util.isCanvasTouch(x, y) || util.isModelTouch(x, y)) return

    this.x = x
    this.y = y

    this.canvas.renderModels()
  }
}
